#!/usr/bin/python
"""
  SZARP SCADA
  $Id$
  2009 Pawel Palucha <pawel@praterm.pl>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA


  Script creates nagios3 hosts and services configuration based on current
  SZARP configurations found.
"""

SZARPLIB = "/opt/szarp/lib"
import sys
sys.path.append(SZARPLIB)
# common szarp-configurations related functions
from szarpnagios import *

import glob
import os
import ConfigParser
import fnmatch
from optparse import OptionParser

def print_host(output, prefix, address):
	"""
	Print szarp host nagios3 definition to output.
	@param output output file
	@param prefix szarp configuration prefix
	@param address host's address
	"""
	alias = param_to_path(get_title(prefix)).replace("_", " ")
	if address != "127.0.0.1":
		alias += " (VPN " + address + ")"
	print >> output, ("""
define host {
	use		szarp-host
	host_name	%s
	alias		%s
	address		%s
}"""
		% (prefix, alias, address))

def get_addresses(iplist):
	"""
	Return dictinary of (prefix -> VPN address) entries for all hosts.
	@param iplist path to OpenVPN ip list file
	"""
	ipp = {}
	for line in open(iplist):
		(prefix,sep,ip) = line.rstrip().partition(',')
		(ipp1, sep, ipp2) = ip.rpartition('.')
		ip =  ipp1 + '.' + str(int(ipp2) + 2)
		#if prefix in ips:
		ipp[prefix] = ip
	return ipp

def print_service(output, description, template, hosts):
	"""
	Print nagios service description
	@param output output file
	@param description nagios service description
	@param template nagios service template to use
	@param hosts list of hosts for service
	"""
	print >> output, ("""
define service {
	service_description	%s
	use			%s
	host_name		%s
}

define servicedependency {
	hostgroup_name			szarp-hosts
	dependent_host_name		%s
	service_description		Current data available
	dependent_service_description	%s
	notification_failure_criteria	w,u,c
}

""" % (
		description, template, ",".join(hosts), ",".join(hosts), description
		))

# options parsing
usage="%prog [options]\n%prog scans all available SZARP configurations and creates list of\nhosts and services for nagios monitoring server.\nNagios should be manually reloaded after new configuration is generated."
parser = OptionParser(usage=usage)
parser.add_option("-o", "--output", dest="outfile", metavar="OUTFILE", 
		default="/etc/nagios3/conf.d/szarp-hosts.cfg",
		help="output nagios configuration file, use '-' for standard output, default is %default")
parser.add_option("-v", "--vpn", dest="vpn", action="store_true", default=False,
		help="get real hosts addresses from OpenVPN IP list, without this option 127.0.0.1 is used for all hosts")
parser.add_option("-i", "--ip-list", dest="iplist", metavar="IPLIST",
		default="/etc/openvpn/ipp.txt",
		help="path to OpenVPN IP addresses list for -v options, default is %default")
parser.add_option("-f", "--config-file", dest="conffile", metavar="CONFFILE", default="/etc/szarp/szarp-nagios.cfg",
		                help="read configuration from CONFFILE, it should contain section [Main] with parameter 'ignored' - space separated list of ignored SZARP configurations; default is %default")

(options, args) = parser.parse_args()

# read config file
config = ConfigParser.SafeConfigParser()
config.read(options.conffile)
ignored = config.get('Main', 'ignored').split()

if options.outfile == "-":
	output = sys.stdout
else:
	output = open(options.outfile, "w")

if options.vpn:
	ipp = get_addresses(options.iplist)
else:
	ipp = {}
devices = {}
max_devices = 0
prefixes = get_prefixes(ignored)
print >> output, "# WARNING - DO NOT EDIT - THIS FILE IS GENERATED BY update-nagios.py COMMAND"
for prefix in prefixes:
	print_host(output, prefix, ipp.get(prefix, '127.0.0.1'))
	tests = get_test_params(prefix)
	devices[prefix] = len(tests)
	if len(tests) > max_devices:
		max_devices = len(tests)

for i in range(1, max_devices+1):
	hosts = [host for host in prefixes if devices[host] >= i]
	print_service(output, "Device %d" % i, "szarp-device-service", hosts)

